package com.voicecall.voicecall.utils;

import com.google.gson.reflect.TypeToken;
import com.voicecall.voicecall.domain.TaskRequest;
import com.voicecall.voicecall.domain.TaskResponse;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.*;

/**
 * Created by cosmos on 2017/10/17.
 */
@Component
@PropertySource({"classpath:resource.properties"})
@ConfigurationProperties
public class HttpClient {
//    private static Logger log = Logger.getLogger(HttpClient.class);
    private static Logger log =   LoggerFactory.getLogger(HttpClient.class);

    @Value("${ws.url}")
    private static String wsUrl;
    /**
     *
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String body = null;

        log.info("create httppost:" + url);

        HttpPost post = postForm(url, params);

        try {
            body = invoke(httpclient, post);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //httpclient.cl
        httpclient.getConnectionManager().shutdown();

        return body;
    }

    /**
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String body = null;

        log.info("create httppost:" + url);

        HttpGet get = new HttpGet(url);
        get.setHeader("Host","api.e-truck.com.cn");
        get.setHeader("apikey","NJ2WSZDZNF2HK2LXGB2GMNLIONSW64DT");
        get.setHeader("Content-Type","application/json");
        get.setHeader("Accept","application/AES.256.CBC.PKCS7");
        try {
            body = invoke(httpclient, get);
        } catch (IOException e) {
            e.printStackTrace();
        }

        httpclient.getConnectionManager().shutdown();

        return body;
    }



    /**
     *
     * @param httpclient
     * @param httpost
     * @return
     */
    private static String invoke(CloseableHttpClient  httpclient,
                                 HttpUriRequest httpost) throws IOException {

        CloseableHttpResponse response = sendRequest(httpclient, httpost);
        String body = paseResponse(response);

        return body;
    }


    /**
     *
     * @param response
     * @return
     */
    private static String paseResponse(CloseableHttpResponse response) throws IOException {
        log.info("get response from http server..");
        HttpEntity entity = response.getEntity();

        log.info("response status: " + response.getStatusLine());
        ContentType contentType= ContentType.getOrDefault(entity);

        //contentType.getCharset();

        String charset = contentType.getCharset().displayName();
        log.info(charset);

        String body = null;
        try {
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            log.info(body);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();
        }

        return body;
    }


    /**
     *
     * @param httpclient
     * @param httpost
     * @return
     */
    private static CloseableHttpResponse sendRequest(CloseableHttpClient httpclient,
                                                     HttpUriRequest httpost) {
        log.info("execute post...");
        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    private static HttpPost postForm(String url, Map<String, String> params){

        HttpPost httpost = new HttpPost(url);
        httpost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        Set<String> keySet = params.keySet();
        for(String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }

        try {
            log.info("set utf-8 form entity to httppost");
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return httpost;
    }

    public static String postForGate(String url,String webid,String dis_id){

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String body = null;
        url = "http://172.16.19.171:8000/proxies/portal/reservation/"+webid+"/dis/"+dis_id+"/contacts";
        log.info("create httppost:" + url);

        body = get(url);

//        try {
//            body = invoke(httpclient, post);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        //httpclient.cl
        httpclient.getConnectionManager().shutdown();

        return body;
    }

    /*
    private static void post(){


        Map params = new HashMap();
        Person p = new Person();
        p.setName("name");
        params.put("0",JsonUtils.objectToJson(p));
        TaskResponse taskResponse= new TaskResponse();
        taskResponse.setMessage("测试");
        taskResponse.setBizId("123");
        taskResponse.setStatus("0");
        taskResponse.setResult(params);
        String taskResponseJson = JsonUtils.objectToJson(taskResponse);

        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        URI uri = null;
        try {
            uri = new URI("http://172.16.90.99:8085/scada-front-web/tos/callback");

            StringEntity s = new StringEntity(taskResponseJson.toString(), "UTF-8");


            HttpUriRequest register = RequestBuilder.post().setUri(uri).setEntity(s).build();
            register.setHeader("Content-Type","application/json;charset=utf-8");
            CloseableHttpResponse response = httpclient.execute(register);
            HttpEntity entity =response.getEntity();
            String body = null;
            body = EntityUtils.toString(entity);
            System.out.println(body);
            //HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("callback_info", taskResponseJson).build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
*/

    public static <T> T postITF(String bizName, String activeName, String dispatchServiceName, String params, Type typeOfT, StringBuffer message){
        String msg = null;
        /*
        try {

            msg = java.net.URLEncoder.encode(params,"UTF-8");
            System.out.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        */
        msg = params;
        //List<TaskRequest> taskRequestes = new ArrayList<TaskRequest>();
        //for (int i=0;i<1;i++) {
        TaskRequest taskRequest = new TaskRequest();
        //taskRequest.setActiveName("GET_YARD_AREA_LIST");//查询服务
        taskRequest.setActiveName(activeName); //修改服务
        taskRequest.setBizName(bizName);
        taskRequest.setBizId(UUID.randomUUID().toString());
        taskRequest.setTaskDispatchServiceName(dispatchServiceName);
        //taskRequest.setTaskDispatchServiceName("wsdMonitorService");
        taskRequest.setDbName("A:B");
        taskRequest.setTaskId(UUID.randomUUID().toString());
        Map<String,Object> map = new HashMap<>();
        map.put("0",msg);
        map.put("1","");

        taskRequest.setParams(map);
        //taskRequestes.add(taskRequest);
        //}
        String result = GsonUtils.getGson().toJson(taskRequest,new TypeToken<TaskRequest>(){}.getType());


        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        URI uri = null;
        CloseableHttpResponse response = null;
        try {

//            uri = new URI(AppResource.get("ws.url"));
            uri = new URI(wsUrl);

            StringEntity s = new StringEntity(result, "UTF-8");


            //HttpUriRequest register = RequestBuilder.post().setUri(uri).setEntity(s).build();
            HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("client_params",result).build();
            //register.setHeader("Content-Type","application/json;charset=utf-8");
            response = httpclient.execute(register);
            HttpEntity entity =response.getEntity();
            String body = null;
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            //System.out.println(java.net.URLDecoder.decode(body,"UTF-8"));
            //String resultx = java.net.URLDecoder.decode(body,"UTF-8");

            TaskResponse taskResponse = GsonUtils.getGson().fromJson(body,TaskResponse.class);
            String itfmsg = taskResponse.getMessage();
            if (!itfmsg.equals("success")){
                message.append(itfmsg);
                return null;
            }else{
                //String resultx = java.net.URLDecoder.decode((String)taskResponse.getResult().get("0"));
                String resultx = (String)taskResponse.getResult().get("0");
                /*
                int dindex = resultx.indexOf("data");
                int sindex = resultx.indexOf("status");
                int mindex = resultx.indexOf("msg");

                int sd = sindex - dindex;
                int md = mindex - dindex;
                String data = "";
                if (sd > 0 && sd < md ) { //data 在最前面
                    data = resultx.substring(dindex+5,sindex-2);
                    data = data.replace("\"","'");
                    resultx = resultx.substring(0,dindex+5) + data + resultx.substring(sindex-2);
                }else if (md > 0 && md < sd){
                    data = resultx.substring(dindex+5,mindex-2);
                    data = data.replace("\"","'");
                    resultx = resultx.substring(0,dindex+5) + data + resultx.substring(mindex-2);
                }else if(sd < 0 && md > 0){ //中间 后面是msg
                    data = resultx.substring(dindex+5,mindex-2);
                    data = data.replace("\"","'");
                    resultx = resultx.substring(0,dindex+5)+ data + resultx.substring(mindex-2);
                }else if (md < 0 && sd > 0){ //中间 后面是msg
                    data = resultx.substring(dindex+5,sindex-2);
                    data = data.replace("\"","'");
                    resultx = resultx.substring(0,dindex+5)+ data + resultx.substring(sindex-2);
                }else{
                    data = resultx.substring(dindex+5);
                    resultx = resultx.substring(0,dindex+5)+data;
                }
                */
                /*
                try {
                    resultx = java.net.URLDecoder.decode(resultx,"UTF-8");
                }catch (Exception e)
                {

                }
                */
                Result result1 =GsonUtils.getGson().fromJson( resultx,Result.class);
                if(result1.getStatus().equals("error")){
                    message.append(result1.getMsg());
                    return null;
                }else{
                    System.out.println(result1.getData());

                    return GsonUtils.getGson().fromJson(result1.getData().toString(),typeOfT);
                }
                //System.out.println(result1);
            }
            //taskResponse.getResult();
            //return java.net.URLDecoder.decode(body,"UTF-8");
            //HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("callback_info", taskResponseJson).build();
        } catch (URISyntaxException | IOException e) {

            e.printStackTrace();
        }finally {
            try {
                if (response != null){
                    response.close();
                }

                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static String postITF(String bizName, String activeName, String dispatchServiceName, String params, StringBuffer message){
        String msg = null;
        /*
        try {

            msg = java.net.URLEncoder.encode(params,"UTF-8");
            System.out.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        */
        msg = params;
        //List<TaskRequest> taskRequestes = new ArrayList<TaskRequest>();
        //for (int i=0;i<1;i++) {
        TaskRequest taskRequest = new TaskRequest();
        //taskRequest.setActiveName("GET_YARD_AREA_LIST");//查询服务
        taskRequest.setActiveName(activeName); //修改服务
        taskRequest.setBizName(bizName);
        taskRequest.setBizId(UUID.randomUUID().toString());
        taskRequest.setTaskDispatchServiceName(dispatchServiceName);
        //taskRequest.setTaskDispatchServiceName("wsdMonitorService");
        taskRequest.setDbName("A:B");
        taskRequest.setTaskId(UUID.randomUUID().toString());
        Map<String,Object> map = new HashMap<>();
        map.put("0",msg);
        map.put("1","");

        taskRequest.setParams(map);
        //taskRequestes.add(taskRequest);
        //}
        String result = GsonUtils.getGson().toJson(taskRequest,new TypeToken<TaskRequest>(){}.getType());


        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        URI uri = null;
        CloseableHttpResponse response = null;
        try {

//            uri = new URI(AppResource.get("ws.url"));
            uri = new URI(wsUrl);

            StringEntity s = new StringEntity(result, "UTF-8");


            //HttpUriRequest register = RequestBuilder.post().setUri(uri).setEntity(s).build();
            HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("client_params",result).build();
            //register.setHeader("Content-Type","application/json;charset=utf-8");
            response = httpclient.execute(register);
            HttpEntity entity =response.getEntity();
            String body = null;
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            //System.out.println(java.net.URLDecoder.decode(body,"UTF-8"));
            //String resultx = java.net.URLDecoder.decode(body,"UTF-8");

            TaskResponse taskResponse = GsonUtils.getGson().fromJson(body,TaskResponse.class);
            String itfmsg = taskResponse.getMessage();
            if (!itfmsg.equals("success")){
                message.append(itfmsg);
                return null;
            }else{
                //String resultx = java.net.URLDecoder.decode((String)taskResponse.getResult().get("0"));
                String resultx = (String)taskResponse.getResult().get("0");
                return resultx;
            }
            //taskResponse.getResult();
            //return java.net.URLDecoder.decode(body,"UTF-8");
            //HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("callback_info", taskResponseJson).build();
        } catch (URISyntaxException | IOException e) {

            e.printStackTrace();
        }finally {
            try {
                if (response != null){
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static String postITFForMap(String url, String bizName, String activeName, String dispatchServiceName,  Map<String,Object> map, StringBuffer message){
        String msg = null;
        List<TaskRequest> taskRequestes = new ArrayList<TaskRequest>();
        for (int i=0;i<1;i++) {
            TaskRequest taskRequest = new TaskRequest();
            //taskRequest.setActiveName("GET_YARD_AREA_LIST");//查询服务
            taskRequest.setActiveName(activeName); //修改服务
            taskRequest.setBizName(bizName);
            taskRequest.setBizId(UUID.randomUUID().toString());
            taskRequest.setTaskDispatchServiceName(dispatchServiceName);
            //taskRequest.setTaskDispatchServiceName("wsdMonitorService");
            taskRequest.setDbName("A:B");
            taskRequest.setTaskId(UUID.randomUUID().toString());
            taskRequest.setParams(map);
            taskRequestes.add(taskRequest);
        }
        String result = GsonUtils.getGson().toJson(taskRequestes,new TypeToken<List<TaskRequest>>(){}.getType());

        System.out.println("params: "+result);
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        URI uri = null;
        CloseableHttpResponse response = null;
        try {
            System.out.println(url);
            uri = new URI(url);
            //System.out.println(uri);
            //uri = new URI(AppResource.get("itf.url"));

            StringEntity s = new StringEntity(result, "UTF-8");


            //HttpUriRequest register = RequestBuilder.post().setUri(uri).setEntity(s).build();
            HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("client_params",result).build();
            //register.setHeader("Content-Type","application/json;charset=utf-8");
            response = httpclient.execute(register);
            HttpEntity entity =response.getEntity();
            String body = null;
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            //System.out.println(java.net.URLDecoder.decode(body,"UTF-8"));
            //String resultx = java.net.URLDecoder.decode(body,"UTF-8");

            TaskResponse taskResponse = GsonUtils.getGson().fromJson(body,TaskResponse.class);
            String itfmsg = taskResponse.getMessage();
            System.out.println("itfmsg: "+itfmsg);
            if (!itfmsg.equals("success")){
                message.append(itfmsg);
                return null;
            }else{
//                String resultx = java.net.URLDecoder.decode((String)taskResponse.getResult().get("0"));
                String resultx = (String)taskResponse.getResult().get("0");
                System.out.println("resultx: "+resultx);

                return resultx;
            }
            //taskResponse.getResult();
            //return java.net.URLDecoder.decode(body,"UTF-8");
            //HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("callback_info", taskResponseJson).build();
        } catch (URISyntaxException | IOException e) {

            e.printStackTrace();
        }finally {
            try {
                if (response != null){
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static String postITFByNormal(String url, String bizName, String activeName, String dispatchServiceName,
                                         String params1, String params2, String params3, String params4, StringBuffer message){
        String msg = null;
        /*
        try {

            msg = java.net.URLEncoder.encode(params,"UTF-8");
            System.out.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        */
        msg = params1;
        List<TaskRequest> taskRequestes = new ArrayList<TaskRequest>();
        for (int i=0;i<1;i++) {
            TaskRequest taskRequest = new TaskRequest();
            //taskRequest.setActiveName("GET_YARD_AREA_LIST");//查询服务
            taskRequest.setActiveName(activeName); //修改服务
            taskRequest.setBizName(bizName);
            taskRequest.setBizId(UUID.randomUUID().toString());
            taskRequest.setTaskDispatchServiceName(dispatchServiceName);
            //taskRequest.setTaskDispatchServiceName("wsdMonitorService");
            taskRequest.setDbName("A:B");
            taskRequest.setTaskId(UUID.randomUUID().toString());
            Map<String,Object> map = new HashMap<>();
            map.put("0", msg);
            if (!org.springframework.util.StringUtils.isEmpty(params2)) {
                map.put("1", params2);
                if (!org.springframework.util.StringUtils.isEmpty(params3)) {
                    map.put("2", params3);
                    if (!org.springframework.util.StringUtils.isEmpty(params4)) {
                        map.put("3", params4);
                    }
                }
            }
            taskRequest.setParams(map);
            taskRequestes.add(taskRequest);
        }
        String result = GsonUtils.getGson().toJson(taskRequestes,new TypeToken<List<TaskRequest>>(){}.getType());

        System.out.println("params: "+result);
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        URI uri = null;
        CloseableHttpResponse response = null;
        try {
            System.out.println(url);
            uri = new URI(url);
            //System.out.println(uri);
            //uri = new URI(AppResource.get("itf.url"));

            StringEntity s = new StringEntity(result, "UTF-8");


            //HttpUriRequest register = RequestBuilder.post().setUri(uri).setEntity(s).build();
            HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("client_params",result).build();
            //register.setHeader("Content-Type","application/json;charset=utf-8");
            response = httpclient.execute(register);
            HttpEntity entity =response.getEntity();
            String body = null;
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            //System.out.println(java.net.URLDecoder.decode(body,"UTF-8"));
            //String resultx = java.net.URLDecoder.decode(body,"UTF-8");

            TaskResponse taskResponse = GsonUtils.getGson().fromJson(body,TaskResponse.class);
            String itfmsg = taskResponse.getMessage();
            System.out.println("itfmsg: "+itfmsg);
            if (!itfmsg.equals("success")){
                message.append(itfmsg);
                return null;
            }else{
//                String resultx = java.net.URLDecoder.decode((String)taskResponse.getResult().get("0"));
                String resultx = (String)taskResponse.getResult().get("0");
                System.out.println("resultx: "+resultx);

                return resultx;
            }
            //taskResponse.getResult();
            //return java.net.URLDecoder.decode(body,"UTF-8");
            //HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("callback_info", taskResponseJson).build();
        } catch (URISyntaxException | IOException e) {

            e.printStackTrace();
        }finally {
            try {
                if (response != null){
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static String postITFX(String url, String bizName, String activeName, String dispatchServiceName, String params, StringBuffer message){
        String msg = null;
        /*
        try {

            msg = java.net.URLEncoder.encode(params,"UTF-8");
            System.out.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        */
        msg = params;
        List<TaskRequest> taskRequestes = new ArrayList<TaskRequest>();
        for (int i=0;i<1;i++) {
            TaskRequest taskRequest = new TaskRequest();
            //taskRequest.setActiveName("GET_YARD_AREA_LIST");//查询服务
            taskRequest.setActiveName(activeName); //修改服务
            taskRequest.setBizName(bizName);
            taskRequest.setBizId(UUID.randomUUID().toString());
            taskRequest.setTaskDispatchServiceName(dispatchServiceName);
            //taskRequest.setTaskDispatchServiceName("wsdMonitorService");
            taskRequest.setDbName("A:B");
            taskRequest.setTaskId(UUID.randomUUID().toString());
            Map<String,Object> map = new HashMap<>();
            map.put("0",msg);
            map.put("1","");

            taskRequest.setParams(map);
            taskRequestes.add(taskRequest);
        }
        String result = GsonUtils.getGson().toJson(taskRequestes,new TypeToken<List<TaskRequest>>(){}.getType());

        System.out.println("params: "+result);
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        URI uri = null;
        CloseableHttpResponse response = null;
        try {
            System.out.println(url);
            uri = new URI(url);
            //System.out.println(uri);
            //uri = new URI(AppResource.get("itf.url"));

            StringEntity s = new StringEntity(result, "UTF-8");


            //HttpUriRequest register = RequestBuilder.post().setUri(uri).setEntity(s).build();
            HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("client_params",result).build();
            //register.setHeader("Content-Type","application/json;charset=utf-8");
            response = httpclient.execute(register);
            HttpEntity entity =response.getEntity();
            String body = null;
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            //System.out.println(java.net.URLDecoder.decode(body,"UTF-8"));
            //String resultx = java.net.URLDecoder.decode(body,"UTF-8");

            TaskResponse taskResponse = GsonUtils.getGson().fromJson(body,TaskResponse.class);
            String itfmsg = taskResponse.getMessage();
            System.out.println("itfmsg: "+itfmsg);
            if (!itfmsg.equals("success")){
                message.append(itfmsg);
                return null;
            }else{
//                String resultx = java.net.URLDecoder.decode((String)taskResponse.getResult().get("0"));
                String resultx = (String)taskResponse.getResult().get("0");
                System.out.println("resultx: "+resultx);

                return resultx;
            }
            //taskResponse.getResult();
            //return java.net.URLDecoder.decode(body,"UTF-8");
            //HttpUriRequest register = RequestBuilder.post().setUri(uri).addParameter("callback_info", taskResponseJson).build();
        } catch (URISyntaxException | IOException e) {

            e.printStackTrace();
        }finally {
            try {
                if (response != null){
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    /*
    public static void main(String[] args){
        //String bizName = "VMS_MS";
        //String activeName = "SAVE_VESSEL_WORK_RULE_LIST";

        String bizName = "SYS_MS";
        String activeName = "GET_SYS_ROLE_PERMISSION_LIST";

        String dispatchServiceName = "wsdMonitorService";

        StsCams stsCams = new StsCams();
        List<Camera> cameras = new ArrayList<Camera>();
        Camera camera1 = new Camera();
        camera1.setCamId("1");
        Camera camera2 = new Camera();
        camera2.setCamId("2");

        cameras.add(camera1);
        cameras.add(camera2);

        stsCams.setStsId("测试");
        stsCams.setCams(cameras);
        //String msg = JsonUtils.objectToJson(stsCams);

        String msg = GsonUtils.getGson().toJson(stsCams);
        msg = msg.replace("\"","'");
        System.out.println(msg);
        //"[{'_state':'modified','yaaAreano':'07','yaaYbkBlockid':null,'yaaCraft':'0','yaaStbayno':1,'yaaEdbayno':89,'yaaRows':10,'yaaTiers':6,'yaaHeight':15.6,'yaaBayway':'DU','yaaRowway':'RL','yaaLaneway':'DU','yaaOuttrknum':5,'yaaIntrknum':5,'yaaTotaltrknum':99,'yaaUseage':'D','yaaOuteryardfg':'N','yaaBerthno':null,'yaaAlertnum':100,'yaaBaydistance':70,'yaaFitstatus':null,'yaaTermno':'1','yaaUserareano':null,'yaaAreax':233,'yaaAreay':135,'yaaLength':31,'yaaWidth':292.5,'yaaMultibay':99,'yaaInsertdt':1453168215000,'yaaInsertuser':'Y4TOS','yaaLstupddt':null,'yaaLstupusler':null,'yaaOefg':null,'yaaUsefg':null},{'_state':'modified','yaaAreano':'08','yaaYbkBlockid':null,'yaaCraft':'1','yaaStbayno':1,'yaaEdbayno':103,'yaaRows':10,'yaaTiers':6,'yaaHeight':15.6,'yaaBayway':'DU','yaaRowway':'RL','yaaLaneway':'DU','yaaOuttrknum':5,'yaaIntrknum':5,'yaaTotaltrknum':99,'yaaUseage':'D','yaaOuteryardfg':'N','yaaBerthno':null,'yaaAlertnum':100,'yaaBaydistance':70,'yaaFitstatus':null,'yaaTermno':'1','yaaUserareano':null,'yaaAreax':270.5,'yaaAreay':109,'yaaLength':31,'yaaWidth':338,'yaaMultibay':99,'yaaInsertdt':1453168218000,'yaaInsertuser':'Y4TOS','yaaLstupddt':null,'yaaLstupuser':null,'yaaOefg':null,'yaaUsefg':null},{'_state':'modified','yaaAreano':'09','yaaYbkBlockid':null,'yaaCraft':'2','yaaStbayno':1,'yaaEdbayno':107,'yaaRows':10,'yaaTiers':6,'yaaHeight':15.6,'yaaBayway':'DU','yaaRowway':'RL','yaaLaneway':'DU','yaaOuttrknum':5,'yaaIntrknum':5,'yaaTotaltrknum':99,'yaaUseage':'D','yaaOuteryardfg':'N','yaaBerthno':null,'yaaAlertnum':100,'yaaBaydistance':70,'yaaFitstatus':null,'yaaTermno':'1','yaaUserareano':null,'yaaAreax':322.5,'yaaAreay':109,'yaaLength':31,'yaaWidth':351,'yaaMultibay':99,'yaaInsertdt':1453168221000,'yaaInsertuser':'Y4TOS','yaaLstupddt':null,'yaaLstupuser':null,'yaaOefg':null,'yaaUsefg':null},{'_state':'removed','yaaAreano':'x10','yaaYbkBlockid':null,'yaaCraft':'0','yaaStbayno':1,'yaaEdbayno':103,'yaaRows':10,'yaaTiers':6,'yaaHeight':15.6,'yaaBayway':'DU','yaaRowway':'RL','yaaLaneway':'DU','yaaOuttrknum':5,'yaaIntrknum':5,'yaaTotaltrknum':99,'yaaUseage':'D','yaaOuteryardfg':'N','yaaBerthno':null,'yaaAlertnum':100,'yaaBaydistance':70,'yaaFitstatus':null,'yaaTermno':'1','yaaUserareano':null,'yaaAreax':360,'yaaAreay':135,'yaaLength':31,'yaaWidth':338,'yaaMultibay':99,'yaaInsertdt':1453168222000,'yaaInsertuser':'Y4TOS','yaaLstupddt':null,'yaaLstupuser':null,'yaaOefg':null,'yaaUsefg':null}]"
        //msg = "[{\\\"_state\\\":\\\"removed\\\",\\\"bthBthno\\\":\\\"9\\\",\\\"bthSeq\\\":1,\\\"bthBthnm\\\":\\\"[0xe6][0xb3][0x8a][0xe4][0xbd][0x8d][0xe4][0xb9][0x9d]\\\",\\\"bthStartpst\\\":0,\\\"bthEndpst\\\":200,\\\"bthLogicstartpst\\\":0,\\\"bthLogicendpst\\\":200,\\\"bthDepth\\\":17.0,\\\"bthAngle\\\":0.0,\\\"bthRemark\\\":null,\\\"bthValidfg\\\":\\\"Y\\\",\\\"bthTermcd\\\":null,\\\"bthTermno\\\":\\\"1\\\",\\\"bthInsertdt\\\":1445394159000,\\\"bthInsertuser\\\":null,\\\"bthLstupddt\\\":1445394159000,\\\"bthLstupuser\\\":\\\"TOPS\\\",\\\"bthRdepth\\\":20.0}]";
        //msg = "{'fltId':'2368','vmpPlandt':'2016-09','lnrId':'3012,3013,3014,3015,3016'}";
        msg = "["
                + "{'_state':'added','fltSlnId':'29769','fltNo':'10','fltSchdul':'2','fltCycle':'3','fltInitdt':'2016-09-02 10:10'"
                + ",'BpsLinersPojo':[{'_state':'added','lnrVslCd':'CSCL SPRxx','lnrNo':'1'}]"
                + ",'BpsPortOfCallingsPojo':[{'_state':'added','pocOrder':'1','pocPotPortcd':'TTPOS','pocEdicode':'xx'}]"
                + "}"
                + "]" ;

        String param = "[{\\\"_state\\\":\\\"modified\\\",\\\"rvDomain\\\":\\\"VMS_LOADCNTRCHANGE\\\",\\\"rvLowValue\\\":\\\"G04\\\",\\\"rvMeaning\\\":\\\"是否允许自动沉箱\\\",\\\"rvHighValue\\\":\\\"Y\\\",\\\"rvAbbreviation\\\":\\\"Y\\\",\\\"rvEmeaning\\\":\\\"G\\\",\\\"rvEdicode\\\":\\\"N\\\",\\\"rvValidfg\\\":\\\"Y\\\",\\\"rvInsertdt\\\":1384826289000,\\\"rvInsertuser\\\":null,\\\"rvLstupddt\\\":1386308607000,\\\"rvLstupuser\\\":\\\"Jack\\\",\\\"rvStdCode\\\":null}]";

        String param1 = "{\\\"page\\\":0,\\\"rows\\\":0,\\\"sidx\\\":null,\\\"sord\\\":null,\\\"isSearch\\\":null,\\\"offSet\\\":0,\\\"rules\\\":[[{\\\"field\\\":\\\"surUseraccount\\\",\\\"op\\\":\\\"eq\\\",\\\"value\\\":\\\"'TOPS'\\\",\\\"dataType\\\":null},{\\\"field\\\":\\\"surPassword\\\",\\\"op\\\":\\\"eq\\\",\\\"value\\\":\\\"'1'\\\",\\\"dataType\\\":null}]]}";

        String p2 = "{\"page\":0,\"rows\":0,\"sidx\":null,\"sord\":null,\"isSearch\":null,\"offSet\":0,\"rules\":[]}]";
        StringBuffer message = new StringBuffer();
        List result = postITF(bizName, activeName,dispatchServiceName, param1,new TypeToken<List<Test>>(){}.getType(), message );

        System.out.println(message.toString());


        Map params = new HashMap();
        Person p = new Person();
        p.setName("name");
        params.put("0",JsonUtils.objectToJson(p));
        TaskResponse taskResponse= new TaskResponse();
        taskResponse.setMessage("test");
        taskResponse.setBizId("123");
        taskResponse.setStatus("0");
        taskResponse.setResult(params);
        String taskResponseJson = JsonUtils.objectToJson(taskResponse);
        Map pa = new HashMap();
        pa.put("callback_info",taskResponseJson);

        post("http://172.16.90.99:8085/scada-front-web/tos/callback",pa);


    }

*/
    /**
     * 模拟请求
     *
     * @param url       资源地址
     * @param map   参数列表
     * @param encoding  编码
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

        System.out.println("请求地址："+url);
        System.out.println("请求参数："+nvps.toString());

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }
}

class Result{
    String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    String msg;
    Object data;
}